<?php
/**
 * Created by PhpStorm.
 * User: 13790
 * Date: 2018/3/22
 * Time: 10:53
 */

namespace app\common\model;

use app\common\validate\Role as ValidateRole;

class Role extends Base
{
    protected $autoWriteTimestamp = true ;

    public static function init(){
//        //添加成功后回调函数
//        self::event('after_insert',function($role){
//            $a_ids = $role['a_ids'];
//            foreach($a_ids as $k=>$v){
//                db('role')->save($role['a_ids']);
//
//            }
//        });
        //编辑成功之后回调函数
//        self::event('after_update',function($role){
//            $res = db('role_auth')->where('role_id','=',$role['id'])->delete();
//
//            foreach($role['a_ids'] as $k=>$v){
//                db('role_auth')->insert([
//                    'role_id' => $role['id'],
//                    'auth_id' =>$v
//                ]);
//            }
////        });
    }

    public function sel(){
        $data = $this
            ->alias('a')
            ->field('a.*,group_concat(c.admin_user) admin_users')
            ->join('admin_role b','a.id = b.role_id','LEFT')
            ->join('admin c','b.admin_id = c.id','LEFT')
            ->group('a.id')
            ->select();
        return $data;
    }

    public function addData(){
        $dt=input('post.');

        $dd=$dt['a_ids'];

        $s2=implode(',',$dd);

        $dt['a_ids']=$s2;
        //验证
        $validate=new ValidateRole();
        if (!$validate->scene('add')->check($dt)){
            return $validate->getError();
        }



        //添加数据


        $res=$this->allowField(true)->save($dt);
        if (!$res){
            return '添加失败';
        }
        return true;

    }
    public function editData(){
        $dt = input('post.');
        //验证数据
        $validate = new ValidateRole();
        //验证编辑的场景
        if(!$validate->scene('edit')->check($dt)){
            return $validate->getError();
        }

        $res = $this->allowField(true)->save($dt,['id'=>$dt['id']]);
        dump($res);exit();
        if(!$res){
            return '更新失败！';
        }
        return true;

    }
}